<?php
class RecommendCourse extends AppModel {
	var $name = 'RecommendCourse';
	var $useTable = 'recommend_courses';
	var $primaryKey = 'id';
	var $displayField = 'course_id';

	/**
	 * Add course from the list recommend
	 * @param $ids
	 */
	function addRecommend($ids) {
		$recommendCourses = $this->find('list');
		$rank = $this->getMaxRank();
		if (!is_array($ids)) {
			$ids = array($ids);
		}
		foreach ($ids as $id) {
			if (!in_array($id, $recommendCourses)) {
				$rank++;
				$data = array(
					'id' => null,
					'course_id' => $id,
					'rank' => $rank,
				);
				$this->save($data);
			}
		}
	}

	/**
	 * Remove the course from the list recommend
	 * @param $ids
	 */
	function removeRecommend($ids) {
		$conditions = array(
			'course_id' => $ids,
		);
		$this->deleteAll($conditions, false, false);
	}

	/**
	 * Get current max rank of recommend course
	 * @return int
	 */
	function getMaxRank() {
		$options = array(
			'order' => 'rank DESC',
		);
		$recommend = $this->find('first', $options);
		if ($recommend) {
			return $recommend['RecommendCourse']['rank'];
		} else {
			return 0;
		}
	}
}